package org.dromara.wms.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.io.IoUtil;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.dromara.common.core.config.RuoYiConfig;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.minio.utils.StringUtils;
import org.dromara.common.minio.utils.file.FileUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.pdfprint.bean.InDetailPdfData;
import org.dromara.common.pdfprint.bean.InOrderPdfData;
import org.dromara.common.pdfprint.service.PDFService;
import org.dromara.common.pdfprint.utils.bean.BeanUtils;
import org.dromara.common.web.core.BaseService;
import org.dromara.wms.domain.WmsOrder;
import org.dromara.wms.domain.WmsOrderLine;
import org.dromara.wms.mapper.WmsOrderLineMapper;
import org.dromara.wms.service.WmsOrderServiceImpl;
import org.dromara.wms.service.WmsStockService;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static org.dromara.common.satoken.utils.LoginHelper.getUsername;

/**
 * 订单管理
 * @author wenrui Su
 * @date 2024-03-24
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/wms/order")
public class WmsOrderController extends BaseService {

  private final WmsOrderServiceImpl orderService;
  private final PDFService pdfService;
  private final WmsOrderLineMapper lineMapper;
  /**
   * 查询订单管理列表
   */
  @SaCheckPermission("wms:order:list")
  @GetMapping("/list")
  public TableDataInfo<WmsOrder> partnerList(WmsOrder order, PageQuery pageQuery) {
    return orderService.queryPageList(order, pageQuery);
  }


  /**
   * 导出订单管理列表
   */
  @SaCheckPermission("wms:order:export")
  @Log(title = "订单管理", businessType = BusinessType.EXPORT)
  @PostMapping("/export")
  public void export(WmsOrder bo, HttpServletResponse response) {
    List<WmsOrder> list = orderService.queryList(bo);
    ExcelUtil.exportExcel(list, "订单管理", WmsOrder.class, response);
  }

  /**
   * 获取订单管理详细信息
   * @param id 主键
   */
  @SaCheckPermission("wms:order:query")
  @GetMapping("/{id}")
  public R<WmsOrder> getInfo(@NotNull(message = "主键不能为空") @PathVariable Long id) {
    return R.ok(orderService.queryById(id));
  }

  /**
   * 新增订单管理
   */
  @SaCheckPermission("wms:order:add")
  @Log(title = "订单管理", businessType = BusinessType.INSERT)
  @RepeatSubmit()
  @PostMapping()
  public R<Void> add(@Validated(AddGroup.class) @RequestBody WmsOrder bo) throws WmsStockService.emptyException {
    return orderService.insertByBo(bo);
  }

  /**
   * 修改订单管理
   */
  @SaCheckPermission("wms:order:edit")
  @Log(title = "订单更新", businessType = BusinessType.UPDATE)
  @RepeatSubmit()
  @PutMapping()
  public R<Void> edit(@Validated(EditGroup.class) @RequestBody WmsOrder bo) {
    return toAjax(orderService.updateByBo(bo));
  }

  /**
   * 订单执行
   */
  @SaCheckPermission("wms:order:exec")
  @Log(title = "订单执行", businessType = BusinessType.UPDATE)
  @RepeatSubmit()
  @PutMapping("/execOrder")
  public R<Void> exec(@Validated(EditGroup.class) @RequestBody WmsOrder bo) throws WmsStockService.emptyException {
    return orderService.execByBo(bo);
  }

  /**
   * 转采购订单
   */
  @SaCheckPermission("wms:order:turn")
  @Log(title = "订单执行", businessType = BusinessType.UPDATE)
  @RepeatSubmit()
  @PutMapping("/turnOrder")
  public R<Void> turn(@Validated(EditGroup.class) @RequestBody List<WmsOrder> bo) throws WmsStockService.emptyException {
//    return orderService.turnOrder(bo);
    return orderService.NewTurnOrder(bo);
  }

  /**
   * 订单冲销
   */
  @SaCheckPermission("wms:order:back")
  @Log(title = "订单冲销", businessType = BusinessType.UPDATE)
  @RepeatSubmit()
  @PutMapping("/backOrder")
  public R<Void> back(@Validated(EditGroup.class) @RequestBody WmsOrder bo) {
    return orderService.backByBo(bo);
  }

  /**
   * 财务结算
   */
  @SaCheckPermission("wms:order:finance")
  @Log(title = "财务结算", businessType = BusinessType.UPDATE)
  @RepeatSubmit()
  @PutMapping("/financialSettlement")
  public R<Void> financialSettlement(@Validated(EditGroup.class) @RequestBody WmsOrder bo) {
    return orderService.financialSettlement(bo);
  }


  /**
   * 删除订单管理
   *
   * @param ids 主键串
   */
  @SaCheckPermission("wms:order:remove")
  @Log(title = "订单管理", businessType = BusinessType.DELETE)
  @DeleteMapping("/{ids}")
  public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
    return toAjax(orderService.deleteWithValidByIds(List.of(ids), true));
  }

  /**
   * 查询测试从列表======================Line表的路由服务==========================
   */
  @SaCheckPermission("wms:order:list")
  @GetMapping("/lineList")
  public TableDataInfo<WmsOrderLine> lineList(WmsOrderLine bo, PageQuery pageQuery) {
    return orderService.queryLinePageList(bo, pageQuery);
  }
  @SaCheckPermission("wms:order:print")
  @GetMapping("printInOrder/{orderId}")
  public void printInOrder( jakarta.servlet.http.HttpServletResponse response, @PathVariable Long orderId) throws Exception{

    //输出流
    OutputStream out = response.getOutputStream();
    //入库单1898753942275813378
//    WmsOrder order = orderService.queryById(orderId);
    WmsOrder order = orderService.queryById(1898753942275813378l);
//    StockInOrder order = stockInOrderService.selectStockInOrderByOrderId(orderId);
    if(order != null){
      //更新入库单状态
//      order.setOrderStatus(OrderStatusEnum.PRINTED.getValue());
//      order.setUpdateBy(getUsername());
//      order.setUpdateTime(DateUtils.getNowDate());
//      stockInOrderService.updateStockInOrder(order);
      //入库单
      InOrderPdfData orderPdfData = new InOrderPdfData();
      BeanUtils.copyBeanProp(orderPdfData, order);
      orderPdfData.setOrderNo(order.getId().toString());
      orderPdfData.setOrderType(order.getWmsType());
      orderPdfData.setCreateBy(order.getCreateBy().toString());
      WmsOrderLine lineBo = new WmsOrderLine();
      lineBo.setId(order.getId());

      //入库单详情
      List<InDetailPdfData> detailPdfDataList = new ArrayList<>();
      InDetailPdfData detailPdfData = null;
      List<WmsOrderLine> detailList = lineMapper.queryLinePageList(lineBo);
//      List<WmsOrderLine> detailList = order.getLine();
//      List<StockInDetail> detailList = stockInDetailService.selectStockInDetailListByOrderNo(order.getOrderNo());
      if(CollectionUtils.isNotEmpty(detailList)){
        for(WmsOrderLine detail : detailList){
          detailPdfData = new InDetailPdfData();
          BeanUtils.copyBeanProp(detailPdfData, detail);
          detailPdfData.setUnitName("个");
          detailPdfData.setQuantity(new BigDecimal(500.0));
          detailPdfData.setUnitPrice(new BigDecimal(100.0));
          detailPdfDataList.add(detailPdfData);
        }
      }


      response.setContentType(MediaType.APPLICATION_PDF_VALUE+ "; charset=UTF-8");
//      FileUtils.setAttachmentResponseHeader(response, "fd");
      try(
        // 入库单数据
        // 获取文件流
        InputStream inputStream = new FileInputStream(new File(pdfService.printInOrder(orderPdfData, detailPdfDataList)));
      ) {
        // 获取文件长度
        int available = inputStream.available();
        // 直接写流到前端
        IoUtil.copy(inputStream, response.getOutputStream(), available);
        // 设置文件长度
        response.setContentLength(available);
      } catch (Exception e) {
        // 如果oss异常无法连接则将数据直接返回
        throw new ServiceException(e.getMessage());
      }
    }
  }



  /**
   * 删除测试从
   * @param lineIds 主键串
   */
  @SaCheckPermission("wms:order:remove")
  @Log(title = "测试从", businessType = BusinessType.DELETE)
  @DeleteMapping("/lineId/{lineIds}")
  public R<Void> removeLine(@NotEmpty(message = "主键不能为空") @PathVariable Long[] lineIds) {
    return toAjax(orderService.deleteWithValidByLineIds(List.of(lineIds), true));
  }

  /**
   * pc商城新增订单管理
   */
  @SaCheckPermission("wms:order:add")
  @Log(title = "订单管理", businessType = BusinessType.INSERT)
  @RepeatSubmit()
  @PostMapping("/pcCart")
  public R<Void> pcAdd(@Validated(AddGroup.class) @RequestBody WmsOrder bo) throws WmsStockService.emptyException {
    return orderService.pcInsertByBo(bo);
  }
}
